package arrayandstring;
/**
 * https://leetcode-cn.com/problems/convert-1d-array-into-2d-array/
 */
public class E2022_Construct2DArray {
    /**
     * 时间复杂度 O(n) 空间复杂度 O(m*n) 
     */
    public int[][] construct2DArray(int[] original, int m, int n) {
        if(original.length != m*n) {
            return new int [0][];
        }
        int[][] target = new int[m][n];
        for (int i = 0; i < original.length; ++i) {
            target[i/n][i%n] = original[i];
        }
        return target;
    }
    /**
     * 官方解法
     * 时间复杂度 O(n) 空间复杂度 O(m*n) 
     */
    public int[][] construct2DArray1(int[] original, int m, int n) {
        if(original.length != m*n) {
            return new int [0][];
        }
        int[][] target = new int[m][n];
        for (int i = 0; i < original.length; i += n) {
            /**
             * System.arraycopy(src, srcPos, dest, destPos, length);
             * 
             * src：要复制的数组(源数组)
             * srcPos：复制源数组的起始位置
             * dest：目标数组
             * destPos：目标数组的下标位置
             * length：要复制的长度
             */
            System.arraycopy(original, i, target[i/n], 0, n);
        }    
        return target;
    }
}
